7.2 JavaScript as a programming language

  1. Motivations
    • Is JavaScript a general purpose programming language?
    • What is the purpose of JavaScript in web applications?

  2. Read all in JavaScript Introduction.
    • What can you do with JavaScript?
      • Reacting to events, such as mouse clicking
      • Contents
      • Attributes
      • Styles, i.e., CSS properties
  3. Read all in JavaScript Where To.
    • Which tag is used to include JavaScript code?
    • Where can you place the above tag including JavaScript code, in <body> or <head>?
    • Can you place scripts in multiple places? If so, is it a good programming habit?
    • Study the 1st example carefully. What is the onclick attribute for? The use of getElementById() and onclick is one idea how the JS code and HTML, i.e., DOM (Document Object Model) communicate.
    • How to include external script files? What file extension is used?
  4. Read all in JavaScript Output.
    • List the four different ways to display data.
    • What represents the browser and the application document window? What represents the application document, i.e., HTML elements and CSS rules?
    • What are window and document? What do they represent?
    • We will study BOM (Browser Object Model) and DOM (Document Object Model) later again in detail.
    • What is going to happen if document.write() is used after an HTML document is fully loaded?
    • What is console?
    • What does document.getElementById() return?
    • Trial 1: Let's try to change innerHTML to display a message, and the background-color. window.alert() is also used in this example.



  5. Read all in JavaScript Statements.
    • What are code blocks?
    • What are functions?
    • In the last example, is not the function definition used after the invocation of the function? Not really. You need to remember that the function definition is executed (interpreted) by the browser, and sometime later the button will be clicked by the user and the function will be invoked.
  6. Read all in JavaScript Syntax.
    • Which keyword is used to declare variables?
    • Do you have to specify data type when variables are declared?
    • In the first example, what if the script is inserted before the last <p> element?
    • Make any syntax error, and open the console. What can you see?
  7. Intermediate summary - JavaScript and HTML elements, i.e., DOM
    • What have you learned?
      • window, document
      • document.getElementById()
      • window.alert()
      • domobject.innerHTML, domobject.style
      • var
      • Atributes: id, style, onclick
    • How to control HTML elements?
      1. The onclick attribute in an HTML element.
      2. -> The function responding to 'onlick'
      3. In the function, get the element object using the id of the element.
      4. -> Update the element's attributes/content/styles, or read them.
      5. Here is an example.
        <script>
            function start_game() {
                var size = document.getElementById('size').value;
                document.getElementById('output_message').innerHTML = 'If you expect everything, you will get everything.';
                // _TWTG_initialize(size);
            }
        </script>
        ...
        Size: <input id='size' type='number' min='2' max='5' value='3'></input>
        <button id='start_button' onclick='start_game()'>Start the game</button>
        <p id='output_message'></p>
        ...
        
    • How to debug? One good idea is to print some variables and messages. How?
      • window.alert()
      • Console with concole.log()
      • document.write()
  8. Read all in JavaScript Comments.
  9. Read all in JavaScript Variables.
    • Can '$' be used in identifiers?
    • What is 'undefined'? Is it a kind of value?
  10. Read all in JavaScript Operators.
    • Which operator is used to concatenate two strings?
    • How to do interger division?
    • Trial 1.5: Let's try to evaluate "10 + 20 * 30". What result do you exepect?


  11. Read all in JavaScript Data Types.
    • What is the data type of the result of addition of a number and a string?
    • How are array and objects defined?
    • How are they different?
    • What does 'JS has dynamic types.' mean?
    • What does 'typeof' do?
    • How are 'undefined' and "" different?
  12. Read all in JavaScript Comparison and Logical Operators.
    • What is the result of 'x = 5; x == "5";'?
    • Do you still remember how the six bitwise operators work?
    • What does 'But JavaScript uses 32-bit signed numbers.' mean?
    • There is another bitwise operator, called unsigned right shift, that is used for unsigned numbers. -1 >>> 0 will give you 4294967295. Do you remember the maximum number using 32-bit singed integer?
  13. Read all in JavaScript If...Else Statements.
  14. Read all in JavaScript Switch Statement.
  15. Read all in JavaScript Arrays.
    • [...] is used for ???
    • {...} is used for ???
    • Two types of arrays?
    • Are arrays objects?
    • How to count the number of elements in a linear array?
    • How to count the properties in an object?
    • Let data be an array. Is data[i] a variable?
    • Trial 1.6: Let's read a positive integer, n, from the user. Let's read n values from the user and save them into an array. Let's compute the average and display it in a <p>.


  16. Read all in JavaScript For Loop and JavaScript For In
    • Study the last example carefully for the for/in loop.
    • Can the for/in loop be used for regular linear arrays? You can try with the above example after you change the object to an array. Here is an example.
      var course = ['comp2680', 'comp3540', 'comp4620'];
      var person = {fname:"John", lname:"Doe", age:25}; 
      
      var str = "<table>";
      str += "<tr>";
      for (let p in person)
          str += '<td>' + person[p] + '</td>';
      str += '</tr>';
      
      str += "<tr>";
      for (let p in course)
          str += '<td>' + course[p] + '</td>';
      str += '</tr>';
      
      person[0] = 'Tom';
      person[1] = 'Williams';
      person[2] = '22';
      
      str += "<tr>";
      for (let p in person)
          str += '<td>' + person[p] + '</td>';
      str += '</tr>';
      str += '</table>';
      
      window.alert(str);
      
    • Trial 1.9: Let's try the code in the above example.


    • Trial 2: Let's try to count the properties in an associative array, i.e., an object. You need to define a function, named tr2_count().


    • Trial 2.5: Let's try to list the properties and their values in an associative array, i.e., object. You need to define a function, named tr2_5_list().


  17. Read all in JavaScript While Loop.
    • Can you always change a while loop to a for loop? Try to change the last example to use a for loop.
    • Can you always change a for loop to a while loop? Try to change the 2nd last example to use a while loop.
  18. Read all in JavaScript Break and Continue.
    • Explain the difference between the break and continue statements. Trace the output in the first two examples.
    • Let's not use labels. The use of labels could be harmful in structured programming.
  19. Intermediate summary - How is JavaScript different from Java?
    • Declaration of variables
    • Objects
    • Arrays
    • Interaction with DOM
    • What else?

  20. Read all in JavaScript Functions.
    • How to define a function?
    • Do you think every function has to return a value?
    • Why do you use functions?
    • Study the 2nd last example carefully. How are toCelsius and toCelsius() different?
    • How about this?
      function toCelsius(f) { return 5 / 9 * (f - 32); }
      temp = toCelsius;
      document.write(temp(66));
      
    • Trial 2.6: Let's try to write a function to check if a given number is a prime number. (Note that a prime number is a natural number that is divisible by only 1 and itself. Write another function that reads a number from the user using prompt() and check if the number is a prime number using the above function.


    • Trial 2.7: Let's read a positive integer, n, from the user.
      Let's write a function that reads n values from the user, save them into an array and returns the array. n is passed to the function as an argument.
      Let's compute the average using another function. An array is passed to the function as an argument.
      Let's display the return value from the above function.


  21. Read all in JavaScript Objects.
    • What operator is used access members, i.e., properties and methods, in an object?
    • Give two examples how to access members.
      var person = {
          firstName:"John",
          lastName:"Doe",
          age:50,
          eyeColor:"blue",
          getFullName: function() { return this.firstName + " " + this.lastName; }
      };
      document.write(person.age + '<br>');
      document.write(person['age'] + '<br>');  // Objects behave like arrays, and arrays are objects.
      document.write(person.fullName() + '<br>');
      document.write(person['getFullName']() + '<br>');  // Objects behave like arrays, and arrays are objects.
      
    • Trial 3: Let's try the above code.


  22. Read all in JavaScript Scope.
    • What is scope?
    • How are local and global scopes different?
    • Where are all the global variables defined?
    • What if the var keyword is not used for a variable in a function? Is the variable local or global?
    • Are function arguments global?

  23. Read all in JavaScript Array Methods.
    • Did you do the exercises at the bottom in the above link?
    • toString()
    • join(), split()
    • pop(), push()
    • shift(), unshift()
    • How to delete an element?
    • sort(), reverse(), ...
    • ...
    • How to copy an array?
    • How to find the maximum/minimum?
    • How to find the 2nd maximum/minimum?
    • Trial 4: Let's try to implement a queue data structure.


  24. Read all in JavaScript Strings.
    • Did you do the exercises at the bottom in the above link?
    • Many properties and methods - length, ...
    • How to check if a string contains a substring?
    • How to remove whitespaces from both ends of a string? Here is an example.
      var str = '  Amazing Spiderman! \n';
      alert('**' + str + '**');
      str = str.trim();
      alert('**' + str + '**');
      
    • How to convert a string to an array?
  25. Read all in JavaScript String Methods.
    • Did you do the exercises at the bottom in the above link?
  26. Read all in JavaScript Numbers.
    • Did you do the exercises at the bottom in the above link?
    • How to express the positive infinity and the negative infinity?
    • What is NaN?
    • List the five Number properties.
    • How to obtain the maximum number that you can use?
  27. Read all in JavaScript Number Methods.
    • Did you do the exercises at the bottom in the above link?
    • How to round a number with a specified number of decimals? E.g., 1234.34567.toFixed(2); x.toFixed(2);
    • How to convert a string to a number? E.g., Number('234')
  28. Read all in JavaScript Math Object.
    • Did you do the exercises at the bottom in the above link?
    • Many useful methods - min(), max(), round(), random(), ceil(), floor(), ...
    • Many useful constants - E, PI, SQRT2, ...
    • Many useful Math methods - sin(), cos(), log(), pow(), ...
    • Trial 5: Let's try to the integer division.


    • Trial 6: Let's try to a random number in [5, 50]. This example is very important. You may remember the n-Puzzle game. When you select the size of the board and start the game, an initial board that is prepared using random numbers is displayed.



  29. Summary
    • Structure of web programs
      <!DOCTYPE html>
      <head>
          <style>
              /* CSS rules to style the HTML elements in the body element. */
          </style>
          <script>
              // Variables
              // Control statement, such as assignment, if-else, for, for/in, while, do-while, switch, function invokation statements
              // Functions
              // Functions (event handlers)
              //   Invoked when events are triggered on HTML elements in the body element
              //   Control HTML elements in the body element
          </script>
      </head>
      <body>
          <!-- HTML elements -->
          <!-- Some HTML elements have ids. -->
          <!-- Some HTML elements have onclick='javascript code'. -->
          <script>
          </script>    
      </body>
      </html>
      <script>
      </script>
      
    • You should understand that all the control statements in the script will be interpreted(executed) once. After that, the HTML elements in the body will be rendered and stored in the main memory.
    • Then how can the code in the script control the HTML elements in the body?
    • It is time to move to the next section.

  30. Learning outcomes